<template>
  <div>
    <el-form :label-position="labelPosition" label-width="80px" :model="node">
      <el-form-item label="parent">
        <el-cascader
          style="width:100%;"
          v-model="node.parent_id"
          :props="props"
          :placeholder="String(node.parent||'无')"
          :show-all-levels="false"
          filterable
          clearable
        ></el-cascader>
      </el-form-item>

      <el-form-item label="keyName">
        <el-input v-model="node.keyName" clearable></el-input>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button @click="commitForm" type="primary" round>提交</el-button>
      <router-link to="/keywords">
        <el-button type="primary" round>返回</el-button>
      </router-link>
    </el-row>
  </div>
</template>>

<style>
</style>

<script>
import { requestKeywordsUpdate } from "../api/index";
import { requestKeywordsAdd } from "../api/index";
import { requestKeywordsGetByParent } from "../api/index";

export default {
  name: "keywordsForm",
  methods: {
    commitForm() {
      // console.log("this.node", this.node)
      if (this.$route.query.type == 1) {
        var requestData = {
          id: this.node.id,
          keyName: this.node.keyName,
          parent_id: this.node.parent_id.pop()
        };
        // console.log("requestData", requestData);
        requestKeywordsUpdate(requestData).then(data => {
          this.$message({
            message: data.message,
            type: "success"
          });
          window.history.go(-1);
        });
      } else if (this.$route.query.type == 0) {
        var requestData = {
          keyName: this.node.keyName,
          parent_id: this.node.parent_id.pop()
        };
        // console.log("requestData", requestData);
        requestKeywordsAdd(requestData).then(data => {
          this.$message({
            message: data.message,
            type: "success"
          });
          window.history.go(-1);
        });
      }
    }
  },
  data() {
    return {
      labelPosition: "right",
      node: {
        id: this.$route.query.id,
        keyName: this.$route.query.keyName,
        parent: this.$route.query.parent,
        parent_id: [this.$route.query.parent_id]
      },
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level, value } = node;
          requestKeywordsGetByParent({ parent_id: value }).then(res => {
            // console.log(res)
            const nodes = res.result.map(x => ({
              value: x.id,
              label: x.keyName,
              leaf: x.leaf
            }));
            resolve(nodes);
          });
        },
        checkStrictly: true
      }
    };
  }
};
</script>